//
//  AmuseMenuView.swift
//  DouYuZB
//
//  Created by wangpeng on 2017/2/25.
//  Copyright © 2017年 鼎商动力. All rights reserved.
//

import UIKit

private let kMenuCellID = "kMenuCellID"

class AmuseMenuView: UIView {
    //MARK: - 定义属性
    var groups:[AnchorGroup]?{
        didSet{
            collectionView.reloadData()
        }
    }
    // MARK: 控件属性
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var pageControl: UIPageControl!
    // MARK: 从Xib中加载出来
    override func awakeFromNib() {
        super.awakeFromNib()
        collectionView.register(AmuseMenuViewCell.NibObject(), forCellWithReuseIdentifier: kMenuCellID)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = collectionView.bounds.size
    }
}

// MARK:- 遵守UICollectionView的数据源&代理协议
extension AmuseMenuView : UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if groups == nil  {
            return 0
        }
        let pageNum = ((groups?.count)! - 1) / 8 + 1
        
        pageControl.numberOfPages = pageNum
        
        return pageNum
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // 1.取出Cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell
        //2。给cell赋值
        setupCellDataWithCell(cell: cell, indexPath: indexPath)
        return cell
    }
    
    private func setupCellDataWithCell(cell: AmuseMenuViewCell,indexPath : IndexPath){
        //1.获取起始位置
        let startIndex = indexPath.item * 8
        var endIndex = (indexPath.item + 1) * 8 - 1
        //2.判断数组越界
        if endIndex > groups!.count - 1 {
            endIndex = groups!.count - 1
        }
        //3.取出数据，并且赋值给 Cell
        cell.groups = Array(groups![startIndex...endIndex])
    }
}

extension AmuseMenuView{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        pageControl.currentPage = Int(scrollView.contentOffset.x  / scrollView.bounds.size.width)
    }
}
